package auth

import (
	"net/http"

	pb "gitee.com/jiebaiyou/demo-grpc/protos/auth/v1"
	"github.com/gin-gonic/gin"
)

func RegisterRoutes(r *gin.Engine, c *Client) {
	auth := r.Group("/auth")
	{
		auth.POST("/login", handleLogin(c))
		auth.POST("/register", handleRegister(c))
	}
}

func handleLogin(c *Client) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var req struct {
			Username string `json:"username"`
			Password string `json:"password"`
		}
		if err := ctx.BindJSON(&req); err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		resp, err := c.Login(ctx, &pb.LoginRequest{Username: req.Username, Password: req.Password})
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		ctx.JSON(http.StatusOK, gin.H{"token": resp})
	}
}

func handleRegister(c *Client) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var req struct {
			Username string `json:"username"`
			Password string `json:"password"`
		}
		if err := ctx.BindJSON(&req); err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		resp, err := c.Register(ctx, &pb.RegisterRequest{Username: req.Username, Password: req.Password})
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		ctx.JSON(http.StatusOK, gin.H{"token": resp})
	}
}
